<script lang="ts" setup>
import {
  api,
  getOneByCondition,
  getReadonly,
  insertOne,
  isLoginUserById,
  reSetDialogModel,
  updateOne,
  urls
} from '@/index';

import type { DialogModel, NdeReportReviewRecord } from '@/index.d';
import type { FormInstance, FormRules } from 'element-plus';

const dialogModel = defineModel<DialogModel<NdeReportReviewRecord>>('dialogModel', {
  required: true
});

const { insertForbidden, updateForbidden } = getReadonly(dialogModel.value);

const formData = reactive<NdeReportReviewRecord>({
  id: 0,
  isClosed: false
});

const setFormData = async (res: NdeReportReviewRecord) => {
  formData.id = res.id;
  formData.creator = res.creator;
  formData.createTime = res.createTime;
  formData.updater = res.updater;
  formData.updateTime = res.updateTime;
  formData.reportReference = res.reportReference;
  formData.method = res.method;
  formData.comment = res.comment;
  formData.commentType = res.commentType;
  formData.isClosed = res.isClosed;
  formData.note = res.note;
  formData.reportAttachmentUuid = res.reportAttachmentUuid;
  formData.reportPrepareByUsername = res.reportPrepareByUsername;
  formData.noticeTimes = res.noticeTimes;
  formData.noticeTimesRecent = res.noticeTimesRecent;
  formData.lastNoticeTime = res.lastNoticeTime;
};

const reSetFormData = () => {
  reSetDialogModel(dialogModel);
  formData.id = 0;
  delete formData.reportReference;
  delete formData.method;
  delete formData.comment;
  delete formData.commentType;
  delete formData.reportAttachmentUuid;
  delete formData.reportPrepareByUsername;
  delete formData.noticeTimes;
  delete formData.noticeTimesRecent;
  delete formData.lastNoticeTime;
  formData.isClosed = false;
};

watch(
  () => dialogModel.value.visible,
  value => {
    value && (formData.id = dialogModel.value.id as number);
    !value && reSetFormData();
  },
  {
    immediate: true
  }
);

watch(
  () => formData.id,
  async (value: number | undefined) => {
    if (value) {
      const res = await getOneByCondition<NdeReportReviewRecord>(
        urls.ndeReportReviewRecord,
        'id',
        value
      );
      res && setFormData(res);
    }
  },
  {
    immediate: true
  }
);

const formDataRef = ref<FormInstance>();

interface FormDataRules {
  reportReference: string;
  reportPrepareByUsername: string;
  method: string;
  commentType: string;
  comment: string;
}

const formDataRules = computed(() => {
  switch (dialogModel.value.type) {
    case 'view':
      return reactive({});

    case 'update':
      return reactive<FormRules<FormDataRules>>({
        reportReference: [{ required: true, message: '报告编号不能为空', trigger: 'blur' }],
        reportPrepareByUsername: [{ required: true, message: '编制人员不能为空', trigger: 'blur' }],
        method: [{ required: true, message: '检测方法不能为空', trigger: 'blur' }],
        comment: [{ required: true, message: '审核意见不能为空', trigger: 'blur' }],
        commentType: [{ required: true, message: '意见类型不能为空', trigger: 'blur' }]
      });

    case 'insert':
      return reactive<FormRules<FormDataRules>>({
        reportReference: [{ required: true, message: '报告编号不能为空', trigger: 'blur' }],
        reportPrepareByUsername: [{ required: true, message: '编制人员不能为空', trigger: 'blur' }],
        method: [{ required: true, message: '检测方法不能为空', trigger: 'blur' }],
        comment: [{ required: true, message: '审核意见不能为空', trigger: 'blur' }],
        commentType: [{ required: true, message: '意见类型不能为空', trigger: 'blur' }]
      });
  }
});

const saveFormData = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl
    .validate()
    .then(async valid => {
      if (valid) {
        if (dialogModel.value.id === 0) {
          const res = (await insertOne<NdeReportReviewRecord>(
            urls.ndeReportReviewRecord,
            formData
          )) as NdeReportReviewRecord;
          if (res) {
            setFormData(res);
            dialogModel.value.id = res.id as number;
            dialogModel.value.type = 'update';
            dialogModel.value.change = true;
          }
        } else {
          const tempFormData: NdeReportReviewRecord = {
            id: formData.id,
            reportReference: formData.reportReference,
            reportPrepareByUsername: formData.reportPrepareByUsername,
            method: formData.method,
            comment: formData.comment,
            commentType: formData.commentType,
            noticeTimes: formData.noticeTimes,
            isClosed: formData.isClosed,
            noticeTimesRecent: formData.noticeTimesRecent,
            note: formData.note
          };

          const res = (await updateOne<NdeReportReviewRecord>(
            urls.ndeReportReviewRecord,
            tempFormData
          )) as NdeReportReviewRecord;

          if (res) {
            dialogModel.value.change = true;
            formData.updater = res.updater;
            formData.updateTime = res.updateTime;
            formData.noticeTimes = res.noticeTimes;
            formData.noticeTimesRecent = res.noticeTimesRecent;
            formData.lastNoticeTime = res.lastNoticeTime;
          }
        }
      }
    })
    .catch(res => console.log(res));
};

watch(
  () => formData.reportReference,
  (value: string | undefined) => {
    if (value) {
      if (value.includes('RT') || value.includes('rt')) {
        formData.method = 'RT';
      } else if (value.includes('UT') || value.includes('ut')) {
        formData.method = 'UT';
      } else if (value.includes('CH') || value.includes('ch')) {
        formData.method = 'CH';
      } else if (value.includes('MT') || value.includes('mt')) {
        formData.method = 'MT';
      } else if (value.includes('PT') || value.includes('pt')) {
        formData.method = 'PT';
      } else if (value.includes('LT') || value.includes('lt')) {
        formData.method = 'LT';
      } else if (value.includes('ET') || value.includes('et')) {
        formData.method = 'ET';
      } else if (value.includes('VT') || value.includes('vt')) {
        formData.method = 'VT';
      }
    }
  }
);

const sendNoticeButtonDisable = ref<boolean>(false);
const sendNotice = async () => {
  sendNoticeButtonDisable.value = true;
  const res = await api({
    url: urls.ndeReportReviewRecord + '/sendDingDingNotice/' + formData.id
  });

  if (res.data.status) {
    const data = res.data.body as NdeReportReviewRecord;
    formData.noticeTimes = data.noticeTimes;
    formData.noticeTimesRecent = data.noticeTimesRecent;
    formData.lastNoticeTime = data.lastNoticeTime;
    ElMessage.success(res.data.msg);
    dialogModel.value.change = true;
  } else {
    ElMessage.error(res.data.msg);
  }

  setTimeout(() => {
    sendNoticeButtonDisable.value = false;
  }, 5000);
};
</script>
<template>
  <HqDialogDetail
    :dialog-model="dialogModel"
    @submit="saveFormData(formDataRef)"
    operate-record
    :operation="formData"
  >
    <template #default>
      <el-card shadow="hover">
        <template #header>基本信息</template>
        <template #default>
          <hq-form :model="formData" ref="formDataRef" :rules="formDataRules">
            <el-row :gutter="5">
              <hq-col v-show="false">
                <el-form-item label="id" prop="id">
                  <el-input v-model="formData.id" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="报告编号" prop="reportReference">
                  <el-input v-model="formData.reportReference" :disabled="updateForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="检测方法" prop="method">
                  <el-select
                    v-model="formData.method"
                    placeholder="请选择检测方法"
                    :disabled="updateForbidden"
                  >
                    <HqNdeMethodOptions />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="编制人员" prop="reportPrepareByUsername">
                  <el-select
                    v-model="formData.reportPrepareByUsername"
                    clearable
                    placeholder="请选择编制人员"
                    :disabled="updateForbidden"
                  >
                    <HqUserOptions />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="意见类型" prop="commentType">
                  <el-select
                    v-model="formData.commentType"
                    clearable
                    placeholder="请选择意见类型"
                    :disabled="updateForbidden"
                  >
                    <el-option key="委托错误" label="委托错误" value="委托错误" />
                    <el-option key="违反规程" label="违反规程" value="违反规程" />
                    <el-option key="缺陷描述" label="缺陷描述" value="缺陷描述" />
                    <el-option key="其它原因" label="其它原因" value="其它原因" />
                  </el-select>
                </el-form-item>
              </hq-col>
            </el-row>
            <el-row>
              <el-form-item label="审核意见" prop="comment" style="width: 100%">
                <el-input
                  v-model="formData.comment"
                  type="textarea"
                  :autosize="{ minRows: 5 }"
                  :readonly="updateForbidden"
                />
              </el-form-item>
            </el-row>
          </hq-form>
        </template>
      </el-card>
      <el-card shadow="hover" v-if="formData.id != 0">
        <template #header>钉钉通知</template>
        <template #default>
          <hq-form :model="formData">
            <el-row :gutter="5">
              <hq-col>
                <el-form-item label="通知总次数">
                  <el-input v-model="formData.noticeTimes" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="最近通知次数">
                  <el-input v-model="formData.noticeTimesRecent" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="最近通知时间">
                  <el-input v-model="formData.lastNoticeTime" readonly />
                </el-form-item>
              </hq-col>
            </el-row>
          </hq-form>
        </template>
        <template #footer v-if="isLoginUserById(formData.creator?.id as number)">
          <el-button type="primary" @click="sendNotice" :disabled="sendNoticeButtonDisable">
            发送通知
          </el-button>
        </template>
      </el-card>
      <el-card shadow="hover" v-if="formData.reportAttachmentUuid">
        <template #header>报告附件</template>

        <template #default>
          <HqUploadOne
            :key-word="formData.reportAttachmentUuid"
            :disabled="dialogModel.type !== 'update'"
          />
        </template>
      </el-card>
      <el-card shadow="hover" v-if="formData.id">
        <template #header>跟踪验证</template>
        <template #default>
          <hq-form :model="formData" :rules="formDataRules">
            <el-row>
              <hq-col>
                <el-form-item label="是否关闭" prop="commentType">
                  <el-switch
                    v-model="formData.isClosed"
                    class="mb-2"
                    active-text="已关闭"
                    inactive-text="未关闭"
                    :disabled="updateForbidden"
                  />
                </el-form-item>
              </hq-col>
              <el-form-item label="备注信息" prop="note" style="width: 100%">
                <el-input
                  v-model="formData.note"
                  type="textarea"
                  :autosize="{ minRows: 5 }"
                  :readonly="updateForbidden"
                />
              </el-form-item>
            </el-row>
          </hq-form>
        </template>
      </el-card>
    </template>
  </HqDialogDetail>
</template>
<style lang="scss" scoped></style>
